<template>
    <div class="_page home-page">
        <ul class="note-list">
            <li v-for="itemList in noteDatas" :key="itemList.year">
                <strong>{{ itemList.year }}年</strong>
                <ul class="item-list">
                    <li v-for="(item, index) in itemList.list" :key="index" @click="toPage(item.path)">
                        <div>{{ item.title }}</div>
                        <i></i>
                        <span>{{ item.time }}</span>
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</template>

<script>
import lifeInsights from '@/config/articles/lifeInsights.json'
import readingNotes from '@/config/articles/readingNotes.json'
import workSummary from '@/config/articles/workSummary.json'
import { ref, onMounted, nextTick } from 'vue'
import { useRouter, onBeforeRouteLeave } from 'vue-router'

export default {
    setup () {
        const router = useRouter()
        const noteDatas = ref([])
        const init = () => {
            const list = [...lifeInsights, ...readingNotes, ...workSummary]
            // console.log(list)
            const datas = {}
            let year = ''
            list.forEach(item => {
                year = item.time.slice(0, 4)
                if (!datas[year]) {
                    datas[year] = []
                }
                datas[year].push(item)
            })
            noteDatas.value = Object.keys(datas).map(year => {
                datas[year].sort((a, b) => a.time > b.time ? -1 : 1)
                return {
                    year,
                    list: datas[year]
                }
            })
            noteDatas.value.sort((a, b) => a.year > b.year ? -1 : 1)
            // console.log('noteDatas....', noteDatas)
            nextTick(() => {
                const top = sessionStorage.getItem('home-page-scroll')
                document.body.scrollTop = top ? top - 0 : 0
            })
        }

        const toPage = (path) => {
            router.push({ path })
        }

        onMounted(() => {
            init()
        })

        onBeforeRouteLeave((to, from, next) => {
            sessionStorage.setItem('home-page-scroll', document.body.scrollTop)
            next()
        })

        return {
            noteDatas,
            toPage
        }
    }
}
</script>

<style lang="scss">
    @use "./style.scss";
</style>